﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using Common.Model;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using NLog;
using RestSharp;

namespace Common
{
    public class WebHelper
    {
        static Logger logger = LogManager.GetCurrentClassLogger();
        public WebHelper()
        {
            NLog.Web.NLogBuilder.ConfigureNLog("nlog.config");
        }

        public static bool IsJsonStart(string json)
        {
            if (!string.IsNullOrEmpty(json))
            {
                json = json.Trim('\r', '\n', ' ');
                if (json.Length > 1)
                {
                    char s = json[0];
                    char e = json[json.Length - 1];
                    return (s == '{' && e == '}') || (s == '[' && e == ']');
                }
            }
            return false;
        }

        public static T HttpRequest<T>(RequestModel requestModel)
        {
            if (requestModel == null)
            {
                return default(T);
            }

            try
            {
                var client = new RestClient(requestModel.WebSide);

                var request = new RestRequest(requestModel.Resources, requestModel.Method);

                if (!string.IsNullOrEmpty(requestModel.Token))
                {
                    request.AddHeader("Authorization", "Bearer " + requestModel.Token);
                }

                foreach (KeyValuePair<string, string> kvp in requestModel.Parameters)
                {
                    request.AddParameter(kvp.Key, kvp.Value);
                }

                Task<IRestResponse> result = client.ExecuteAsync(request);

                if (result.Result.StatusCode == System.Net.HttpStatusCode.OK)
                {
                    return JsonConvert.DeserializeObject<T>(result.Result.Content);//(T)Convert.ChangeType(result.Result.Content, typeof(T));
                }
                else
                {
                    return (T)Convert.ChangeType(result.Result.ErrorMessage, typeof(T));
                }
            }
            catch (Exception ex)
            {
                logger.Error($"请求地址失败：{requestModel.WebSide + requestModel.Resources} " + ex.Message);
                return default(T);
            }
        }


        public static string HttpRequest(RequestModel requestModel)
        {
            try
            {
                if (requestModel == null)
                {
                    return "";
                }

                var client = new RestClient(requestModel.WebSide);

                var request = new RestRequest(requestModel.Resources, requestModel.Method);

                if (!string.IsNullOrEmpty(requestModel.Token))
                {
                    request.AddHeader("Authorization", "Bearer " + requestModel.Token);
                }


                if (requestModel.FromType == 0)
                {
                    //【FromForm参数】//application/x-www-form-urlencoded
                    foreach (KeyValuePair<string, string> kvp in requestModel.Parameters)
                    {
                        request.AddParameter(kvp.Key, kvp.Value);
                    }
                }
                else
                {
                    //【FromBody参数】 Content-Type: application/json 
                    request.AddJsonBody(requestModel.Parameters.ToJson());
                }

                //foreach (KeyValuePair<string, string> kvp in requestModel.Parameters)
                //{
                //    request.AddParameter(kvp.Key, kvp.Value);
                //}
            

                Task<IRestResponse> result = client.ExecuteAsync(request);

                if (result.Result.StatusCode == System.Net.HttpStatusCode.OK)
                {
                    return result.Result.Content;
                }
                else
                {
                    return "";
                }
            }
            catch (Exception ex)
            {
                logger.Error($"请求地址失败：{requestModel.WebSide + requestModel.Resources} " + ex.Message);
                return "";
            }


        }


        public static string HttpRequest(string Url, string Token = "")
        {
            try
            {
                var client = new RestClient(Url);
                var request = new RestRequest(Method.GET);

                if (!string.IsNullOrEmpty(Token))
                {
                    request.AddHeader("Authorization", "Bearer " + Token);
                }
                Task<IRestResponse> result = client.ExecuteAsync(request);

                if (result.Result.StatusCode == System.Net.HttpStatusCode.OK)
                {
                    return result.Result.Content;
                }
                else
                {
                    return "";
                }
            }
            catch (Exception ex)
            {
                logger.Error($"请求地址失败：{Url} " + ex.Message);
                return "";
            }


        }
    }
}
